const Koa = require('koa');
const Router = require('koa-router');
const bodyParser = require('koa-bodyparser');
const multer = require('@koa/multer');
const path = require('path');
const fs = require('fs');

const app = new Koa();
const router = new Router();

// CORS 手动实现
app.use(async (ctx, next) => {
    ctx.set('Access-Control-Allow-Origin', '*');
    ctx.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    ctx.set('Access-Control-Allow-Headers', 'Content-Type, Authorization, Accept');
    if (ctx.method === 'OPTIONS') {
        ctx.status = 200;
        return;
    }
    await next();
});

// Body parser
app.use(bodyParser());

// 确保 uploads 目录存在
const uploadsDir = path.join(__dirname, 'uploads');
if (!fs.existsSync(uploadsDir)) {
    fs.mkdirSync(uploadsDir, { recursive: true });
}

// 文件上传配置
const upload = multer({
    dest: uploadsDir,
    limits: { fileSize: 50 * 1024 * 1024 }
});

// 上传路由
router.post('/api/upload/audio', upload.single('audio'), async (ctx) => {
    try {
        console.log('[upload] 收到上传请求');
        if (!ctx.request.file) {
            ctx.status = 400;
            ctx.body = { code: -1, message: '没有收到文件' };
            return;
        }

        const file = ctx.request.file;
        const ext = path.extname(file.originalname);
        const newFilename = file.filename + ext;
        const oldPath = file.path;
        const newPath = path.join(uploadsDir, newFilename);

        fs.renameSync(oldPath, newPath);
        console.log('[upload] ✅ 文件上传成功:', newFilename);

        ctx.body = {
            code: 0,
            message: '上传成功',
            data: {
                url: `/uploads/${newFilename}`,
                filename: newFilename,
                originalName: file.originalname,
                size: file.size
            }
        };
    } catch (error) {
        console.error('[upload] ❌ 上传失败:', error);
        ctx.status = 500;
        ctx.body = { code: -1, message: '上传失败: ' + error.message };
    }
});

app.use(router.routes());
app.use(router.allowedMethods());

// 静态文件 - uploads
app.use(async (ctx, next) => {
    if (ctx.path.startsWith('/uploads/')) {
        const filePath = path.join(uploadsDir, ctx.path.replace('/uploads/', ''));
        console.log('[uploads] 请求:', ctx.path, '-> 文件:', filePath);
        if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
            console.log('[uploads] ✅ 文件存在，返回');
            ctx.type = path.extname(filePath);
            ctx.body = fs.createReadStream(filePath);
            return;
        }
        console.log('[uploads] ❌ 文件不存在');
    }
    await next();
});

// 静态文件 - static
const staticDir = path.join(__dirname, '..', 'static');
console.log('静态文件目录:', staticDir);
console.log('目录是否存在:', fs.existsSync(staticDir));

app.use(async (ctx, next) => {
    if (ctx.path.startsWith('/static/')) {
        const filePath = path.join(staticDir, ctx.path.replace('/static/', ''));
        console.log('[static] 请求:', ctx.path, '-> 文件:', filePath);
        if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
            console.log('[static] ✅ 文件存在，返回');
            ctx.type = path.extname(filePath);
            ctx.body = fs.createReadStream(filePath);
            return;
        }
        console.log('[static] ❌ 文件不存在');
    }
    await next();
});

// 根路由
app.use(async (ctx, next) => {
    if (ctx.path === '/' && ctx.method === 'GET') {
        ctx.body = { message: '音乐服务器运行中', time: new Date().toISOString() };
        return;
    }
    if (ctx.path === '/health' && ctx.method === 'GET') {
        ctx.body = { status: 'ok' };
        return;
    }
    await next();
});

// 404
app.use(async (ctx) => {
    console.log('[404] 未找到:', ctx.path);
    ctx.status = 404;
    ctx.body = { error: 'Not Found', path: ctx.path };
});

const PORT = 3000;
app.listen(PORT, '0.0.0.0', () => {
    console.log('\n' + '='.repeat(60));
    console.log('🎵 音乐服务器已启动！');
    console.log('='.repeat(60));
    console.log(`📡 本地地址: http://localhost:${PORT}`);
    console.log(`📡 网络地址: http://172.29.99.148:${PORT}`);
    console.log(`📁 静态目录: ${staticDir}`);
    console.log(`🎵 测试静态文件: http://172.29.99.148:${PORT}/static/brightest_star.mp3`);
    console.log('='.repeat(60) + '\n');
});
